package com.base.home.act;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.base.commonlib.base.CBaseBarMvpActivity;
import com.base.commonlib.bean.User;
import com.base.commonlib.http.RealNetWorkUtil;
import com.base.commonlib.utils.ToastUtil;
import com.base.home.R;
import com.base.home.databinding.ActivityHomenewBinding;
import com.base.home.presenter.HomeNewPresenter;
import com.base.home.view.HomeNewView;
import com.base.sweb.client.ChromeClientCallbackManager;
import com.base.sweb.client.DefaultWebClient;
import com.base.sweb.client.MiddleWareWebChromeBase;
import com.base.sweb.client.MiddleWareWebClientBase;
import com.base.sweb.client.WebDefaultSettingsManager;
import com.base.sweb.file.DownLoadResultListener;
import com.base.sweb.js.AndroidInterface;
import com.base.sweb.manage.IWebLayout;
import com.base.sweb.manage.SuperWebX5;
import com.base.sweb.progress.BaseIndicatorView;
import com.base.sweb.utils.PermissionInterceptor;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;

/**
 * Created by weikailiang on 2020/3/27.
 */
@Route(path = "/home/homenew")
public class HomeNewActivity extends CBaseBarMvpActivity<HomeNewPresenter> implements HomeNewView {

    private ActivityHomenewBinding mBinding;
    @Autowired
    String title;
    //    @Autowired
//    String detail;
    @Autowired
    String id;
    @Autowired
    String courseRootId;
    @Autowired
    String imgurl;
    @Autowired
    String type;
    protected SuperWebX5 mSuperWebX5;
    boolean isAddJf;
    private MiddleWareWebChromeBase mMiddleWareWebChrome;
    private MiddleWareWebClientBase mMiddleWareWebClient;
    private UMWeb web;


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_homenew;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void init() {
        super.init();
        mBinding = (ActivityHomenewBinding) mRootBinding;
        mPresenter = new HomeNewPresenter(this, this);
        mPresenter.start();
        setBackNavigation();
        Log.e("xxxxx",mPresenter.mUser.getTenantId());
        setRigImg(R.drawable.ic_title_share, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UMImage thumb = new UMImage(mContext, imgurl);
                thumb.compressStyle = UMImage.CompressStyle.QUALITY;
                web = new UMWeb(RealNetWorkUtil.HOST_IP+":8585/kaoshi/index.html#/newsDetail?id=" + id);
                web.setTitle(title.length() > 10 ? (title.substring(0, 10) + "...") : title);//标题
                web.setThumb(thumb);  //缩略图
                web.setDescription(title);//描述
                new ShareAction(HomeNewActivity.this)
                        //.withMedia(web)
                        .setDisplayList(SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.ALIPAY, SHARE_MEDIA.DINGTALK)
                        .addButton("越青山看看", "umeng_sharebutton_custom", "ic_app_white_logo", "ic_app_white_logo")
                        .setShareboardclickCallback(shareBoardlistener)
                        //.setCallback(shareListener)
                        .open();
            }
        });


    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void start() {
        mPresenter.toStudy(id);
        mSuperWebX5 = SuperWebX5.with(this)
                .setSuperWebParent(mBinding.root, new LinearLayout.LayoutParams(-1, -1))
                .customProgress(getIndicatorView())
                .setWebLayout(getWebLayout())
                .setWebSettings(getSettings())
                .setWebViewClient(mWebViewClient)
                .setWebChromeClient(mWebChromeClient)
                .setReceivedTitleCallback(mCallback)
                .setPermissionInterceptor(mPermissionInterceptor)
                .setNotifyIcon(com.base.sweb.R.mipmap.download)
                .useMiddleWareWebChrome(getMiddleWareWebChrome())
                .useMiddleWareWebClient(getMiddleWareWebClient())
                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)
                .interceptUnkownScheme()
                .openParallelDownload()
                .setSecutityType(SuperWebX5.SecurityType.strict)
                .addDownLoadResultListener(mDownLoadResultListener)
                .createSuperWeb()
                .ready()
                .go(getUrl());
        mSuperWebX5.getJsInterfaceHolder().addJavaObject("yookey", new AndroidInterface(mSuperWebX5, mContext));
        webView = mSuperWebX5.getWebCreator().get();
        webView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View view, int i, int i1, int i2, int i3) {
                float webViewContentHeight = webView.getContentHeight() * webView.getScale();
                //WebView的现高度
                float webViewCurrentHeight = (webView.getHeight() + webView.getWebScrollY());

                if ((webViewContentHeight - webViewCurrentHeight) < 10) {
                    if (!isAddJf) {
                        mPresenter.getJifeng(courseRootId,mPresenter.mUser.getTenantId(),type);
                    }
                    isAddJf = true;
                }
            }
        });

    }

    WebView webView;

    private void addImageClickListener(WebView webView) {
        webView.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\"); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "    objs[i].onclick=function()  " +
                "    {  "
                + "       alert(this.src) " +
                "    }  " +
                "}" +
                "})()");

    }

    /**
     * 权限拦截器
     * 在触发某些敏感的 Action 时候会回调该方法， 比如定位触发 。
     * 例如 https//:www.baidu.com 该 Url 需要定位权限， 返回false ，如果版本大于等于23 ， 会动态申请权限 ，true 该Url对应页面请求定位失败。
     * 该方法是每次都会优先触发的 ， 开发者可以做一些敏感权限拦截
     */
    protected PermissionInterceptor mPermissionInterceptor = new PermissionInterceptor() {

        @Override
        public boolean intercept(String url, String[] permissions, String action) {
            return false;
        }
    };

    /**
     * 文件下载结果监听
     */
    protected DownLoadResultListener mDownLoadResultListener = new DownLoadResultListener() {
        @Override
        public void success(String path) {
            Toast.makeText(mContext, "下载成功,存储地址:" + path, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void error(String path, String resUrl, String cause, Throwable e) {
            Toast.makeText(mContext, "下载失败", Toast.LENGTH_SHORT).show();
        }
    };

    /**
     * 获取WebView设置
     */
    public com.base.sweb.client.WebSettings getSettings() {
        return WebDefaultSettingsManager.getInstance();
    }

    /**
     * 获取url
     */
    public String getUrl() {
        String target = RealNetWorkUtil.HOST_IP+":8585/kaoshi/index.html#/newsDetail?id=" + id;
        return target;
    }

    /**
     * 获取网页title
     */
    protected ChromeClientCallbackManager.ReceivedTitleCallback mCallback = new ChromeClientCallbackManager.ReceivedTitleCallback() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (!TextUtils.isEmpty(title)) {
                if (title.length() > 10) {
                    title = title.substring(0, 10) + "...";
                    setBarTitle(title);
                } else {
                    setBarTitle(title);
                }
            }

        }
    };


    /**
     * 获取进度条
     */
    protected WebChromeClient mWebChromeClient = new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }

    };

    /**
     * 采用X5客户端拦截URL
     */
    protected com.tencent.smtt.sdk.WebViewClient mWebViewClient = new com.tencent.smtt.sdk.WebViewClient() {

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }

//        @Override
//        public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
//            sslErrorHandler.proceed();
//            super.onReceivedSslError(webView, sslErrorHandler, sslError);
//
//        }

        @Override
        public boolean shouldOverrideUrlLoading(final WebView view, String url) {
            //intent:// scheme的处理 如果返回false ， 则交给 DefaultWebClient 处理 ， 默认会打开该Activity  ， 如果Activity不存在则跳到应用市场上去.  true 表示拦截
            //例如优酷视频播放 ，intent://play?vid=XODEzMjU1MTI4&refer=&tuid=&ua=Mozilla%2F5.0%20(Linux%3B%20Android%207.0%3B%20SM-G9300%20Build%2FNRD90M%3B%20wv)%20AppleWebKit%2F537.36%20(KHTML%2C%20like%20Gecko)%20Version%2F4.0%20Chrome%2F58.0.3029.83%20Mobile%20Safari%2F537.36&source=exclusive-pageload&cookieid=14971464739049EJXvh|Z6i1re#Intent;scheme=youku;package=com.youku.phone;end;
            //优酷想唤起自己应用播放该视频 ， 下面拦截地址返回 true  则会在应用内 H5 播放 ，禁止优酷唤起播放该视频， 如果返回 false ， DefaultWebClient  会根据intent 协议处理 该地址 ， 首先匹配该应用存不存在 ，如果存在 ， 唤起该应用播放 ， 如果不存在 ， 则跳到应用市场下载该应用 .
            if (url.startsWith("intent://")) {
                return true;
            } else if (url.startsWith("youku")) {
                return true;
            }

            return false;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
        }

        @Override
        public void onPageFinished(final WebView view, String url) {
            super.onPageFinished(view, url);
//            view.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    addImageClickListener(view);
//                }
//            }, 5000);


        }
    };

    protected IWebLayout getWebLayout() {
        return null;
    }

    protected BaseIndicatorView getIndicatorView() {
        return null;
    }


    @Override
    public void onResume() {
        mSuperWebX5.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    public void onPause() {
        mSuperWebX5.getWebLifeCycle().onPause();
        super.onPause();
    }

    public MiddleWareWebChromeBase getMiddleWareWebChrome() {
        return mMiddleWareWebChrome;
    }

    public MiddleWareWebClientBase getMiddleWareWebClient() {
        return mMiddleWareWebClient;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mSuperWebX5.getWebLifeCycle().onDestroy();
        UMShareAPI.get(this).release();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mSuperWebX5.uploadFileResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }


    private ShareBoardlistener shareBoardlistener = new ShareBoardlistener() {
        @Override
        public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {

            if (share_media == null) {
                //根据key来区分自定义按钮的类型，并进行对应的操作
                if (snsPlatform.mKeyword.equals("umeng_sharebutton_custom")) {
                    ARouter.getInstance().build("/look/editlook")
                            .withString("type", "3")//分享都是新闻
                            .withString("courseId", id)//只编辑文字
                            .withString("title", title)//新闻标题
                            .withString("url", getUrl())//新闻地址
                            .withString("imgurl", imgurl)//缩略图
                            .navigation();

                }
            } else {//社交平台的分享行为
                new ShareAction(HomeNewActivity.this)
                        .withMedia(web)
                        .setPlatform(share_media)
                        .setCallback(shareListener)
                        .share();
            }
        }
    };

    //分享回调
    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            showMes("分享成功");
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            showMes("分享失败");
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            showMes("分享取消了");
        }
    };
}
